import { _decorator, animation, Button, Collider2D, color, Color, Component, Contact2DType, instantiate, Label, Node, Prefab, ProgressBar, randomRange, randomRangeInt, Scheduler, Sprite, tween, UIOpacity, Vec3 } from 'cc';
import { BattleManager } from './BattleManager';
import { EntityManager } from './Base/EntityManager';
import { PlayerStateMachine } from './PlayerStateMachine';
import { Context } from './Context';
import { EEvent, EGroup, EState, EntityType, PLAY_AREA, EBuff, EPlayerType, EWuxing, EColor } from './Config/Enum';
import { Core } from './Core/Core';
import { EnemyStateMachine } from './EnemyStateMachine';
import { WallManager } from './WallManager';
import ObjectPoolManager from './Core/ObjectPoolManager';

import { NumberText } from './Core/NumberText';
import { EnemyConfig } from './Config/EnemyConfig';
import { Util } from './Util';
import { EnemyBuffManager } from './BuffManager';
import { EItemType } from './Item/Item';
import { Stun } from './Item/Stun';
import { ResourceManager } from './Core/ResourceManager';
import { PrefabPath } from './Config/ResourceConfig';
import { EnemyBullet } from './EnemyBullet';

const { ccclass, property } = _decorator;

@ccclass('EnemyManager')
export class EnemyManager extends EntityManager {
    // --- 缩放相关属性 ---
    private _startScale
    private _endScale
    private _scaleRange: number = 300;
    private _speedFactor: number = 1;
    // 优化：记录上一次Y坐标，避免每帧重复计算缩放
    private _lastY: number = 0; 

    // --- 节点引用 ---
    sp: Sprite = null!;
    ndHalo: Node = null!;
    
    // --- 状态标志 ---
    isMoving = true
    canAttack = true
    isCounted = false;
    isElite = false;
    isBoss = false;

    // --- 中毒属性 ---
    private poisonStacks: Array<{ damage: number, duration: number }> = [];
    poisonDamagePerStack: number = 0;
    poisonDuration: number = 0;
    poisonTimer: number = 0;
    isPoisoned: boolean = false;
    poisonByPlayer: EntityType;
    
    lbLevel: Label;
    ndLevel: Node;
    level = 1;

    // --- 特殊技能状态 ---
    isReducedDpByShaolinSkill1 = false;

    stateMachine: EnemyStateMachine;
    isInvincible = false;

    gm: BattleManager;
    em: EnemyManager;
    type: EntityType;

    // --- 战斗属性 ---
    ap: number;
    dp: number;
    speed = 100;
    attackSpeed = 100;
    hp = 100;
    maxHp = 100;
    evasion = 0.1;
    attackTarget: Collider2D;
    dropRate = 0.1;

    ndHp: Node = null!;
    spWuxing: Sprite = null!;
    wuxing: EWuxing;
    accuracy: number = 1;
    originalAccuracy: number = 1;

    // --- Buff 管理 ---
    buffManager: EnemyBuffManager;
    originalSpeed: number = 0;
    originalAttackSpeed: number = 0;
    originalIsMoving: boolean = true;
    originalCanAttack: boolean = true;
    originalState: EState = EState.Run;
    
    // --- 各种状态Flag ---
    isFreezed = false;
    isStuned = false;
    isSlowed = false;
    poisonCount = 0;
    burnCount = 0;
    originalDp: number;
    isMissed: boolean;
    isDpDown: boolean;
    isVulnerable: boolean = false; 
    isWeak: boolean;
    originalAp: number;
    isFear: boolean;
    isSilenced: boolean;
    isApDown: boolean;
    isExplosioned: boolean
    isDisarmed: boolean
    isKnockBacked: boolean
    explosionDamage: number = 0


    // --- 远程属性 ---
    // 攻击距离 (0 或 undefined 代表近战)
    attackRange: number = 0;
    // 是否为远程单位
    isRanged: boolean = false;
    // 子弹预制体路径
    bulletPrefabPath: string = '';
    // 城墙节点的Y坐标 (用于远程判断)
    private _targetY: number = -250; 
    // 远程攻击的目标组件缓存
    private _remoteTargetWm: WallManager | null = null;

    // --- [优化] 简单的防重叠参数 (脉冲+阻尼) ---
    private _driftSpeedX: number = 0; // 当前的横向漂移速度
    private _driftDecay: number = 5.0; // 漂移衰减系数（阻尼），越大停得越快
    private _separationPushForce: number = 50; // 弹开的力度（速度）
    private _minDistanceX: number = 30; // X轴最小间距 (半个身位)
    private _minDistanceY: number = 30; // Y轴最小间距
    private _separationInterval: number = 0.2; // 检测间隔
    private _separationTimer: number = 0;

    private _boundaryX: number = 300;

    // 初始化木桩敌人 (保留旧方法以兼容)
    initWoodenEnemy(enemyType: EntityType) {
        const enemyConfig = EnemyConfig[enemyType];
        this.hp = enemyConfig.hp;
        this.dp = enemyConfig.dp;
        this.speed = enemyConfig.speed;
        this.evasion = enemyConfig.evasion;
        this.attackSpeed = enemyConfig.attackSpeed;
        this.ap = enemyConfig.ap;
        this.accuracy = enemyConfig.accuracy || 1;
        this.originalAccuracy = this.accuracy;
        this.isMoving = false

        this.ndHp = this.node.getChildByName("HP");
        this.spWuxing = this.ndHp.getChildByName("Wuxing").getComponent(Sprite);
        this.sp = this.node.getChildByName('Animation').getComponent(Sprite);
        this.ndHalo = this.node.getChildByName("Halo")

        this.ensureStateMachine(enemyType);
        this.state = EState.Idle;

        this.initBuffManager();
    }

    init(enemyType: EntityType, isElite: boolean = false, isBoss: boolean = false) {
        // [错峰计算] 给每个敌人一个随机的初始时间
        this._separationTimer = randomRange(0, this._separationInterval);

        // 初始化边界
        if (Core.Instance.screenBounds) {
            this._boundaryX = Core.Instance.screenBounds.maxX / 2 - 20; // 稍微留点边距
        }

        // [新增] 出生时给一个微小的随机X偏移 (-10 到 10)，形成天然的错落感
        const randomOffsetX = randomRange(-10, 10);
        this.node.setPosition(this.node.position.x + randomOffsetX, this.node.position.y, 0);

        // [重置] 归零漂移速度
        this._driftSpeedX = 0;

        // 立即设置初始缩放
        const startScale = 0.1;
        this.node.setScale(startScale, startScale, 1);

        this.ndHp = this.node.getChildByName("HP");
        this.spWuxing = this.ndHp.getChildByName("Wuxing").getComponent(Sprite);
        this.sp = this.node.getChildByName('Animation').getComponent(Sprite);
        this.ndHalo = this.node.getChildByName("Halo")

        // 设置类型
        this.isElite = isElite;
        this.isBoss = isBoss;

        // 重置状态
        this.reset();

        this.ensureStateMachine(enemyType);
        this.state = EState.Run;
        this.type = enemyType;

        // 设置基础属性及关隘成长
        const enemyConfig = EnemyConfig[enemyType];
        const currentStage = Core.Instance.currentStage;
        
        const hpScale = 1 + (currentStage - 1) * 0.8;
        const dpScale = 1 + (currentStage - 1) * 0.6;
        const apScale = 1 + (currentStage - 1) * 0.1;

        this.speed = enemyConfig.speed;
        this.hp = enemyConfig.hp * hpScale;
        this.maxHp = enemyConfig.hp * hpScale;
        this.attackSpeed = enemyConfig.attackSpeed;
        this.ap = enemyConfig.ap * apScale;
        this.dp = enemyConfig.dp * dpScale;
        this.accuracy = this.originalAccuracy = enemyConfig.accuracy || 1;
        this.evasion = enemyConfig.evasion;
        this.wuxing = enemyConfig.wuxing;

        // 2. === 新增：初始化远程属性 ===
        this.attackRange = enemyConfig.attackRange || 0;
        this.bulletPrefabPath = enemyConfig.bulletPrefab || '';
        
        // 如果有攻击距离且大于0，视为远程
        this.isRanged = this.attackRange > 0;
        
        const wallNode = BattleManager.Instance.ndWall;
        if (wallNode) {
            // 缓存 WallManager 组件，供远程攻击使用
            this._remoteTargetWm = wallNode.getComponent(WallManager);
            
            // 修正目标Y值：城墙中心Y + 城墙碰撞体高度一半(假设50) + 攻击距离
            // 这样敌人会在距离城墙表面 attackRange 的地方停下
            this._targetY = wallNode.position.y + 50; 
        }

        if (this.spWuxing) {
            this.spWuxing.color = color().fromHEX(EColor[this.wuxing]);
        }

        // 应用精英/BOSS加成
        if (this.isElite) {
            this.hp = this.maxHp = this.hp * 2;
            this.ap = this.ap * 2;
            this.dp = this.dp * 2;
            this.speed = this.speed * 1.5;
            this.ndHalo.active = true;
            this.ndHalo.getComponent(Sprite).color = color().fromHEX(EColor.EliteHalo);
            this._endScale = 0.7;
        } else if (this.isBoss) {
            this.ndHalo.active = true;
            this.ndHalo.getComponent(Sprite).color = color().fromHEX(EColor.BossHalo);
            this._endScale = 1;
        } else {
            this._endScale = 0.5;
        }

        // 强制刷新一次缩放
        this._lastY = this.node.position.y + 9999; 
        this.updateScaleByDistance();
    }

    // 辅助方法：确保状态机存在
    private ensureStateMachine(enemyType: EntityType) {
        if (!this.node.getComponent(EnemyStateMachine)) {
            this.fsm = this.node.addComponent(EnemyStateMachine);
        } else {
            this.fsm = this.node.getComponent(EnemyStateMachine)!;
        }
        this.fsm.init(enemyType);
    }

    // 辅助方法：初始化或重置Buff管理器
    private initBuffManager() {
        if (!this.buffManager) {
            this.buffManager = new EnemyBuffManager(this);
        } else {
            this.buffManager.clearAllBuffs();
        }
    }

    private updateScaleByDistance() {
        const currentY = this.node.position.y;
        
        // 优化：如果位置变化极小，跳过计算
        if (Math.abs(currentY - this._lastY) < 1) return;
        this._lastY = currentY;

        const startY = 300;    
        const endY = -250;     
        
        const progress = Math.min(1, Math.max(0, (currentY - startY) / (endY - startY)));
        
        const startScale = 0.3;
        const currentScale = startScale + (this._endScale - startScale) * progress;

        this.node.setScale(currentScale, currentScale, 1);
    }

    reset() {
        // 重置所有状态
        this.isMoving = true;
        this.canAttack = true;
        this.isCounted = false;
        
        // 重置毒
        this.isPoisoned = false;
        this.poisonStacks = [];
        this.poisonDamagePerStack = 0;
        this.poisonDuration = 0;
        this.poisonTimer = 0;
        this.poisonByPlayer = null;

        if (this.ndHp) {
            const pb = this.ndHp.getComponent(ProgressBar);
            if (pb) pb.progress = 1;
        }

        this.initBuffManager();
        
        this.isFreezed = false;
        this.isStuned = false;
        this.isSlowed = false;
        this.isInvincible = false;
        this.isExplosioned = false;
        this.explosionDamage = 0;

        if (this.ndHalo) {
            this.ndHalo.active = false;
        }

        const collider = this.node.getComponent(Collider2D);
        if (collider) {
            collider.enabled = true;
        }

        this.updateColor();
    }
    
    protected onEnable(): void {
        this.stateMachine = this.node.getComponent(EnemyStateMachine);
        this.node.on("EnemyDieAnimationFinished", this.onDieAnimationFinished, this);
        this.node.on("EnemyAttackAnimationFinished", this.onAttackAnimationFinished, this);
        this.node.on(Node.EventType.TOUCH_END, this.onOpenStatus, this);
        
        let collider = this.node.getComponent(Collider2D);
        collider?.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        collider?.on(Contact2DType.END_CONTACT, this.onEndContact, this);
    }

    protected onDisable(): void {
        let collider = this.node.getComponent(Collider2D);
        collider?.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        collider?.off(Contact2DType.END_CONTACT, this.onEndContact, this);
        this.node.off(Node.EventType.TOUCH_END, this.onOpenStatus, this);
        this.node.off("EnemyDieAnimationFinished", this.onDieAnimationFinished, this);
        this.node.off("EnemyAttackAnimationFinished", this.onAttackAnimationFinished, this);
        
        // 停止所有定时器
        this.unscheduleAllCallbacks();
    }

    onDieAnimationFinished() {
        ObjectPoolManager.Instance.ret(this.node);
    }

    onAttackAnimationFinished() {
        // Loop模式下这个可能不会频繁触发，但保留以防万一
    }

    update(dt: number) {
        const scaledDt = dt * this._speedFactor;

        // 1. 低频检测分离 (0.2秒一次)
        this._separationTimer += dt;
        if (this._separationTimer >= this._separationInterval) {
            this._separationTimer = 0;
            this.checkSeparation(); // 执行简化的分离检测
        }

        // 2. [核心] 漂移速度衰减 (阻尼效果)
        // 每一帧让 driftSpeedX 趋向于 0，产生“滑行停止”的效果
        if (Math.abs(this._driftSpeedX) > 0.1) {
            // 手动实现 lerp: current + (target - current) * t
            // dt * _driftDecay 决定了停下来的快慢
            this._driftSpeedX = this._driftSpeedX + (0 - this._driftSpeedX) * dt * this._driftDecay;
        } else {
            this._driftSpeedX = 0;
        }

        // 3. 移动更新
        this.move(scaledDt);
        
        if(this.buffManager) this.buffManager.update(scaledDt);
        this.processPoison(scaledDt);
        this.updateScaleByDistance();
    }

    move(dt) {
        if (this.isMoving) {
            let moveY = -this.speed * dt;

            // [核心] 叠加漂移速度 (X轴)
            // 改变位置后保留在新的X轨道上，不会自动回弹
            let moveX = this._driftSpeedX * dt;

            // [可选] 挤压时的Y轴阻力：如果正在横向漂移，稍微降低一点前进速度
            if (!this.isBoss && Math.abs(this._driftSpeedX) > 1) {
                moveY *= 0.8; 
            }
        
            // === 远程敌人的距离检测 ===
            if (this.isRanged) {
                // 计算与目标的Y轴距离
                const myY = this.node.position.y;
                const distance = myY - this._targetY;

                // 如果进入攻击范围
                if (distance <= this.attackRange) {
                    this.startRangeAttack();
                    return; // 停止移动
                }
            }

            // 坐标赋值与边界限制
            let nextX = this.node.position.x + moveX;
            let nextY = this.node.position.y + moveY;

            // 边界限制，防止被挤出屏幕
            if (nextX > this._boundaryX) nextX = this._boundaryX;
            if (nextX < -this._boundaryX) nextX = -this._boundaryX;

            this.node.setPosition(nextX, nextY, this.node.position.z);
        }
    }

    /**
     * [优化] 简化的分离检测：只给一个瞬时的横向速度 (脉冲)
     */
    private checkSeparation(): void {
        // 如果当前已经有较大的漂移速度在生效中，就不要重复检测了，避免鬼畜
        if (Math.abs(this._driftSpeedX) > 10) return;

        if (!BattleManager.Instance || !BattleManager.Instance.ndEnemies) return;

        const enemies = BattleManager.Instance.ndEnemies.children;
        const myPos = this.node.position;

        // 寻找一个最近的重叠单位即可
        for (let i = 0, len = enemies.length; i < len; i++) {
            const otherNode = enemies[i];
            if (otherNode === this.node || !otherNode.active) continue;

            const dx = myPos.x - otherNode.position.x;
            const dy = myPos.y - otherNode.position.y;

            // 1. Y轴判定：如果Y轴距离拉开了，X轴叠在一起也没关系，视觉上不违和
            if (Math.abs(dy) > this._minDistanceY) continue;

            // 2. X轴判定：真的叠在一起了
            if (Math.abs(dx) < this._minDistanceX) {
                // 3. 决定弹开方向
                // 如果 dx > 0，我在右边，往右弹(1)；否则往左弹(-1)
                // 如果完全重合(dx=0)，随机弹
                let direction = dx > 0 ? 1 : -1;
                if (Math.abs(dx) < 0.1) direction = Math.random() > 0.5 ? 1 : -1;

                // 4. [核心] 直接设置漂移速度 (脉冲)
                // 这是一个瞬时动作，设完就走，不用每帧都算
                this._driftSpeedX = direction * this._separationPushForce;
                
                // 找到一个重叠的就处理并退出，一次只处理一个冲突，避免多方受力乱飞
                break; 
            }
        }
    }

    /**
     * 开始远程攻击模式
     */
    startRangeAttack() {
        this.isMoving = false;
        // 对于远程，我们需要手动设置攻击目标引用，因为没有触发 onBeginContact
        if (this._remoteTargetWm) {
            this.attackTarget = this._remoteTargetWm.getComponent(Collider2D); 
        }

        if (this.isDisarmed) return;

        // 开始攻击循环
        this.schedule(this.attack, this.attackSpeed);
    }

    // 攻击逻辑
    attack() {
        // 1. 如果被控制（眩晕/冰冻）或者没有目标，就停止
        if (!this.canAttack || !this.attackTarget || !this.attackTarget.node.isValid) return;

        // 2. 确保状态是攻击状态
        if (this.state !== EState.Attack) {
            this.state = EState.Attack; 
        }

        // === 分支：远程攻击逻辑 ===
        if (this.isRanged && this.bulletPrefabPath) {
            this.performRangedAttack();
            return;
        }

        // === 分支：近战攻击逻辑 ===
        if (!this.attackTarget || !this.attackTarget.node.isValid) return;
        
        // 3. 基础伤害
        let damage = this.ap;
        
        // 4. 获取城墙组件
        let wm = this.attackTarget.node.getComponent(WallManager);
        if(!wm) return;

        // 5. 命中/闪避判定
        let hitRate = this.accuracy - wm.dodge;
        let isHit = Math.random() < hitRate;

        if (!isHit) {
            NumberText.show("miss", wm.node.worldPosition, Color.GRAY);
            return;
        } else {
            damage = damage * (1 - wm.dp / (wm.dp + 100));
            if (damage <= 0) {
                damage = 1; // 强制保底伤害
            }
        }

        // 7. 施加伤害
        wm.hurt(damage);
    }

    /**
     * 执行远程攻击：生成子弹
     */
    performRangedAttack() {
        if (!this.bulletPrefabPath) return;

        let prefab = ResourceManager.Instance.getResourceCache().get(this.bulletPrefabPath) as Prefab;
        if (!prefab) return;

        const bulletNode = instantiate(prefab); // 建议优化为 ObjectPoolManager.Instance.get
        bulletNode.parent = this.node.parent; // 添加到战场层
        bulletNode.position = this.node.position.clone(); // 从敌人位置发射

        // 初始化子弹
        const bulletComp = bulletNode.getComponent(EnemyBullet);
        if (bulletComp) {
            bulletComp.init(this.ap, this.accuracy, this._remoteTargetWm);
        }
    }

    hurt(value: number, playerType, color: Color = Color.WHITE, scale = 1, times: number = 1, interval: number = 1): void {
        if (this.state === EState.Die) return;
        
        const doHurt = () => {
            if (!this.node || !this.node.isValid) return; // 安全检查

            if (color !== Color.WHITE) {
                NumberText.show(Util.roundToInt(value).toString(), this.node.worldPosition, color, scale);
            } else {
                NumberText.show(Util.roundToInt(value).toString(), this.node.worldPosition, Color.WHITE, scale);
            }
            
            Core.Instance.event.emit(EEvent.DamageDeal, value, playerType);
            this.hp -= value;
            if (this.ndHp && this.ndHp.isValid) {
                this.ndHp.getComponent(ProgressBar).progress = this.hp / this.maxHp;
            }
            
            if (this.hp <= 0 && this.state !== EState.Die) {
                this.directDie();
            }
        };

        if (times === 1) {
            doHurt();
            if(this.isExplosioned){
                this.explosionDamage += value;
            }
            return;
        }

        for (let i = 0; i < times; i++) {
            this.scheduleOnce(() => {
                if (this.state !== EState.Die) doHurt();
            }, i * interval / this._speedFactor);
        }
    }

    directDie(){
        this.hp = 0;
        this.state = EState.Die;
        this.speed = 0;
        
        const collider = this.node.getComponent(Collider2D);
        if (collider) {
            collider.enabled = false;
        }
        
        Core.Instance.event.emit(EEvent.EnemyDie, this);
    }

    setSpeedFactor(factor: number) {
        this._speedFactor = factor;
    }

    getHPPercent(): number {
        return this.hp / this.maxHp;
    }

    // --- Buff 相关 ---

    private updateColor() {
        if(!this.sp) return;

        if (this.burnCount > 0) {
            this.sp.color = color().fromHEX(EColor.Burn);
            return;
        }
        
        if (this.isSlowed) {
            this.sp.color = color().fromHEX(EColor.Slow);
            return;
        }
        
        this.sp.color = Color.WHITE;
    }
    
    silence(){
        if (this.isSilenced) return;
        this.isSilenced = true;
    }

    revertSilence(){
        this.isSilenced = false;
    }

    weak(value: number) {
        if(this.isWeak){return} 
        this.originalDp = this.dp;
        this.dp -= this.dp * value;
        if (this.dp < 0) this.dp = 0;
        this.isWeak = true;
    }

    revertWeak() {
        this.dp = this.originalDp;
        this.isWeak = false;
    }

    fear() {
        if (this.isFear) return;
        this.isFear = true;
        this.sp.getComponent(Sprite).color = Color.YELLOW;

        const totalFearTime = 1.0;
        let elapsedTime = 0;

        const applyRandomMovement = () => {
            if (elapsedTime >= totalFearTime || !this.isFear || !this.node.isValid) {
                this.isFear = false;
                if(this.sp && this.sp.isValid) this.sp.getComponent(Sprite).color = Color.WHITE;
                return;
            }

            const direction = randomRangeInt(1, 4);
            const moveDuration = randomRange(0.1, 0.3);
            const moveDistance = randomRange(30, 60);
            
            let offsetX = 0;
            let offsetY = 0;
            
            switch (direction) {
                case 1: offsetY = moveDistance; break;
                case 2: offsetX = -moveDistance * 0.7; offsetY = moveDistance * 0.7; break;
                case 3: offsetX = moveDistance * 0.7; offsetY = moveDistance * 0.7; break;
            }

            const targetPos = new Vec3(
                this.node.position.x + offsetX,
                this.node.position.y + offsetY,
                this.node.position.z
            );

            tween(this.node)
                .to(moveDuration, { position: targetPos })
                .call(() => {
                    elapsedTime += moveDuration;
                    applyRandomMovement();
                })
                .start();
        };

        applyRandomMovement();
    }

    revertFear() {
        this.isFear = false;
    }

    processPoison(dt: number) {
        if (!this.isPoisoned) return;
        
        this.poisonTimer += dt;
        
        if (this.poisonTimer >= 1) {
            let totalDamage = 0;
            
            // 优化：倒序遍历，移除过期毒层，避免创建新数组
            for (let i = this.poisonStacks.length - 1; i >= 0; i--) {
                const stack = this.poisonStacks[i];
                totalDamage += stack.damage;
                stack.duration -= 1;
                
                if (stack.duration <= 0) {
                    this.poisonStacks.splice(i, 1);
                }
            }
            
            if (totalDamage > 0) {
                this.hurt(totalDamage, this.poisonByPlayer, Color.GREEN);
            }
            
            if (this.poisonStacks.length === 0) {
                this.clearPoison();
            }
            
            this.poisonTimer = 0;
        }
    }

    addPoisonStack(damagePerSecond: number, duration: number, playerType: EntityType) {
        if (!this.isPoisoned) {
            this.isPoisoned = true;
            this.poisonTimer = 0;
            if(this.sp) this.sp.color = Color.GREEN;
        }
        
        this.poisonStacks.push({
            damage: damagePerSecond,
            duration: duration
        });
        
        if (this.poisonStacks.length > 5) {
            let minIndex = 0;
            for (let i = 1; i < this.poisonStacks.length; i++) {
                if (this.poisonStacks[i].damage < this.poisonStacks[minIndex].damage) {
                    minIndex = i;
                }
            }
            this.poisonStacks.splice(minIndex, 1);
        }
        
        this.poisonByPlayer = playerType;
    }

    clearPoison() {
        this.isPoisoned = false;
        this.poisonStacks = [];
        this.poisonDuration = 0;
        this.poisonTimer = 0;
        this.updateColor();
    }

    slow(value: number) {
        if (this.isSlowed) return;
        
        this.originalIsMoving = this.isMoving;
        this.originalCanAttack = this.canAttack;
        this.originalState = this.state;
        this.originalSpeed = this.speed;

        this.state = EState.Idle;
        this.isMoving = false;
        this.canAttack = false;
        this.speed = this.speed * value;
        this.isSlowed = true;

        this.updateColor();
    }

    revertSlow() {
        this.speed = this.originalSpeed;
        this.isMoving = this.originalIsMoving;
        this.canAttack = this.originalCanAttack;
        this.state = this.originalState; // 可能需要检查是否已经死亡
        this.isSlowed = false;
        if(this.state !== EState.Die) this.state = EState.Run;

        this.updateColor();
    }

    freeze() {
        if (this.isFreezed) return;
        
        this.originalIsMoving = this.isMoving;
        this.originalCanAttack = this.canAttack;
        this.originalState = this.state;
        this.isMoving = false;
        this.canAttack = false;
        this.isFreezed = true;
        this.state = EState.Idle;

        const freezeNode = this.node.getChildByName("Freeze");
        if(freezeNode) freezeNode.active = true;
    }

    revertFreeze() {
        this.isMoving = this.originalIsMoving;
        this.canAttack = this.originalCanAttack;
        this.isFreezed = false;
        if(this.state !== EState.Die) this.state = EState.Run;

        const freezeNode = this.node.getChildByName("Freeze");
        if(freezeNode) freezeNode.active = false;
    }

    stun() {
        if (this.isStuned) return;

        this.originalIsMoving = this.isMoving;
        this.originalCanAttack = this.canAttack;
        this.originalState = this.state;
        this.isStuned = true;
        this.state = EState.Idle;
        this.isMoving = false;
        this.canAttack = false;
        if(this.sp) this.sp.getComponent(Sprite).color = color().fromHEX(EColor.Stun);
        
        // 播放stun动画
        const stunNode = ObjectPoolManager.Instance.get(EBuff.Stun);
        if (stunNode) {
            stunNode.setWorldPosition(this.node.worldPosition.x, this.node.worldPosition.y+30, 0);
            const stun = stunNode.getComponent(Stun);
            if (stun) {
                stun.init();
            }
        }

        this.updateColor();
    }

    revertStun() {
        this.isMoving = this.originalIsMoving;
        this.canAttack = this.originalCanAttack;
        this.state = this.originalState;
        this.isStuned = false;
        if(this.state !== EState.Die) this.state = EState.Run;

        this.updateColor();
    }

    miss(ap){
        if(this.isMissed){return}

        this.originalAccuracy = this.accuracy
        this.accuracy *= ap;
        if (this.accuracy < 0) {
            this.accuracy = 0;
        }
        this.isMissed = true;
    }

    revertMiss() {
        this.accuracy = this.originalAccuracy;
        this.isMissed = false;
    }

    defenceDown(value){
        if(this.isDpDown){return}
        this.originalDp = this.dp;
        this.dp -= this.dp * value;
        if (this.dp < 0) {
            this.dp = 0;
        }
        this.isDpDown = true;
    }

    revertDefenceDown() {
        this.dp = this.originalDp;
        this.isDpDown = false;
    }

    attackDown(value){
        if(this.isApDown){return}
        this.originalAp = this.ap;
        this.ap -= this.ap * value;
        if (this.ap < 0) {
            this.ap = 0;
        }
        this.isApDown = true;
    }
    revertAttackDown(){
        this.ap = this.originalAp;
        this.isApDown = false;
    }

    burn(damage: number, playerType: EntityType) {
        this.hurt(damage, playerType, color().fromHEX(EColor.Burn));
        this.burnCount++;
        
        this.updateColor();
        
        this.scheduleOnce(() => {
            this.burnCount--;
            if (this.burnCount <= 0) {
                this.updateColor();
            }
        }, 0.5);
    }

    knockBack() {
        if (this.isKnockBacked) return;
        this.isKnockBacked = true;
        let randomX = randomRangeInt(-10, 10); 
        let randomY = randomRangeInt(0, 10);

        if(this.sp) this.sp.getComponent(Sprite).color = Color.YELLOW;
    
        const targetPos = new Vec3(
            this.node.position.x + randomX,
            this.node.position.y + randomY,
            this.node.position.z
        );

        tween(this.node)
            .to(0.5, { position: targetPos })
            .call(() => {
                this.updateColor();
            })
            .start();
        this.isKnockBacked = false;
    }

    explosion(){
        this.isExplosioned = true;
    }

    revertExplosion(){
        this.isExplosioned = false;
        // 造成爆炸
        if(this.explosionDamage > 0) {
            this.hurt(this.explosionDamage, "null");
        }
    }

    disarm(){
        this.isDisarmed = true;
    }

    revertDisarm(){
        this.isDisarmed = false;
    }

    slashOnce() {
        if(this.sp) this.sp.getComponent(Sprite).color = Color.RED;
        this.scheduleOnce(() => {
            this.updateColor();
        }, 0.1);
    }
    
    onPlayerDataChange() {}

    levelUp() {
        this.level++;
        this.node.setScale(Math.abs(this.node.scale.x) + 0.01, this.node.scale.y + 0.01, 1);
        this.speed += 0.1;
        if(this.lbLevel) this.lbLevel.string = this.level.toString();
    }

    public getLevel(): number {
        return this.level;
    }
    
    private onBeginContact(self: Collider2D, other: Collider2D) {
        // === 如果是远程单位，忽略碰撞导致的的攻击逻辑，防止近身了又触发一次 ===
        if (this.isRanged) return; 

        switch (other.group) {
            case EGroup.WALL:
                this.isMoving = false;
                this.attackTarget = other;
                if(this.isDisarmed) return;
                
                // 立即攻击一次，然后开始循环
                this.schedule(this.attack, this.attackSpeed);
                break;
            default:
                break;
        }
    }

    private onEndContact(self: Collider2D, other: Collider2D) {
        switch (other.group) {
            case EGroup.WALL:
                this.attackTarget = null;
                this.isMoving = true;
                this.unschedule(this.attack);
                if(this.state !== EState.Die) this.state = EState.Run; // 离开墙壁恢复跑动
                break;
            default:
                break;
        }
    }

    onOpenStatus(){
        Core.Instance.currentEnemy = this; 
        if(Context.ndDefault.getChildByName("EnemyStatusView")){
            Context.ndDefault.getChildByName("EnemyStatusView").destroy()
        }
        let prefab = ResourceManager.Instance.getRes<Prefab>(PrefabPath.EnemyStatusView);
        let node = instantiate(prefab);
        node.setParent(Context.ndDefault);
    }
}